package org.hfoss.POCT;

import android.app.ListActivity;
import android.content.ActivityNotFoundException;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
import android.widget.SimpleCursorAdapter.ViewBinder;

public class ListBuildingActivity extends ListActivity implements ViewBinder  {
	private static final String TAG = "ListBuildingActivity";
	private MyDBHelper mDbHelper;
	private Cursor mCursor;  // Used for DB accesses
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
	}
	
	@Override
	protected void onResume() {
		super.onResume();
		fillData();
	}
	
	@Override
	protected void onPause(){
		super.onPause();
		stopManagingCursor(mCursor);
		mDbHelper.close(); // NOTE WELL: Can't close while managing cursor
		mCursor.close();
	}
	
	@Override
	protected void onStop() {
		super.onStop();
		mDbHelper.close();
		mCursor.close();
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		mDbHelper.close();
		mCursor.close();
	}
	
	private int fillData() {
		Log.i(TAG, "filldata: refilling the data");
		mDbHelper = new MyDBHelper(this);
		//TODO: MyDBHelper: 
		String[] columns = MyDBHelper.list_building_data_row;
		int[] views = MyDBHelper.list_building_view_row;
		mCursor = mDbHelper.fetchAllBuildings();
		startManagingCursor(mCursor); // NOTE: Can't close DB while managing cursor
		// CursorAdapter binds the data in 'columns' to the views in 'views' 
		// It repeatedly calls ViewBinder.setViewValue() (see below) for each column
		SimpleCursorAdapter adapter = 
			new SimpleCursorAdapter(this, R.layout.building_list, mCursor, columns, views);
		adapter.setViewBinder(this);
		setListAdapter(adapter); 
		mDbHelper.close();
		Log.i(TAG, "filldata: refilled the data");
		return mCursor.getCount();
	}

	@Override
	protected void onListItemClick(ListView listView, View view, int position, long id) {
		super.onListItemClick(listView, view, position, id);
		Intent intent = new Intent(this, BuildingActivity.class);
		intent.putExtra("building_id", position);
		try {
			startActivity(intent);
		} catch(ActivityNotFoundException e) {
			Log.e(TAG, e.toString());
		}
		
	}
	@Override
	public boolean setViewValue(View view, Cursor cursor, int columnIndex) {
		switch (view.getId()) {
		default:
			return false;
		}
	}

}
